package com.th.cash.th2.userliving

import ai.braininfra.video.utils.ResultData
import android.text.TextUtils
import androidx.lifecycle.viewModelScope
import com.th.basemodel.base.BaseViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import kotlinx.coroutines.flow.debounce
class UserLivingVm : BaseViewModel() {

    private val repository by lazy {
        UserLivingRepository()
    }

    val intentChannel = Channel<UserLivingIntent>(Channel.UNLIMITED)

    //可变状态数据流（读写）（StateFlow替代LiveData，难道每一个页面都需要定义一个）
    private val _uiState = MutableStateFlow<UserLivingState>(UserLivingState.Idle)

    //可观察状态数据流（只读）
    val uiState: StateFlow<UserLivingState> get() = _uiState

    init {
        viewModelScope.launch {
            intentChannel.consumeAsFlow().debounce(500).collect { value ->
                when (value) {
                    is UserLivingIntent.Idle -> {

                    }

                    is UserLivingIntent.LivingInit -> {
                        livingInit(value.request)
                    }

                    is UserLivingIntent.LivingLimit -> {
                        livingLimit(value.request)
                    }

                    is UserLivingIntent.UploadData -> {
                        uploadLiving(value.pid, value.taskId, value.resultData)
                    }

                    else -> {

                    }
                }
            }
        }
    }

    private fun getBody(
        task_id: String,
        actionList: String,
        files: MutableList<ByteArray>
    ): MultipartBody? {
        if (TextUtils.isEmpty(task_id)) {
            return null
        }

        if (TextUtils.isEmpty(actionList)) {
            return null
        }

        val builder = MultipartBody.Builder()

        files.forEachIndexed { index, bytes ->
            val requestBody: RequestBody =
                RequestBody.create("file".toMediaTypeOrNull(), bytes)
            builder.addFormDataPart(
                "file${index + 1}",
                "file-${System.currentTimeMillis()}",
                requestBody
            )
        }

        return builder
            .setType(MultipartBody.FORM)
            .addFormDataPart("task_id", task_id)
            .addFormDataPart("action_list", actionList)
            .build()
    }

    private fun uploadLiving(pid: String, taskId: String, resultData: ResultData) {
        loadStartLoading()
        val body = getBody(taskId, resultData.actionList, resultData.videosBase64)

        if (body == null) {
            loadSuccess()
            return
        }

        viewModelScope.launch {
            val result = repository.uploadLiving(body)

            result.checkResult(success = {
                loadSuccess()

                getLivingRid(it, pid, taskId)

            }, error = {
                loadError(it)
            })
        }

    }

    private fun getLivingRid(result: String?, pid: String, taskId: String) {
        if (TextUtils.isEmpty(result)) {
            return
        }

        viewModelScope.launch {
            loadStartLoading()

            val result = repository.getLivingRid(LivingRidRequest(pid, result!!, taskId))

            result.checkResult(success = {
                loadSuccess()

                saveLiving(SaveLivingRequest(pid, it?.CQlrawbRiscZrNFrSt ?: ""))

            }, error = {
                loadError(it)
            })
        }
    }

    private fun livingInit(request: LivingInitRequest) {
        viewModelScope.launch {
            loadStartLoading()

            val result = repository.initLiving(request)

            result.checkResult(success = {
                loadSuccess()
                _uiState.value = UserLivingState.Init(it!!)
            }, error = {
                loadError(it)
            })
        }
    }

    private fun livingLimit(request: LivingLimitRequest) {
        viewModelScope.launch {
            loadStartLoading()

            val result = repository.livingLimit(request)

            result.checkResult(success = {
                loadSuccess()
                _uiState.value = UserLivingState.StartLiving
            }, error = {
                loadError(it)
            })
        }
    }

    private fun saveLiving(request: SaveLivingRequest) {
        viewModelScope.launch {
            loadStartLoading()

            val result = repository.saveLiving(request)

            result.checkResult(success = {
                loadSuccess()
                _uiState.value = UserLivingState.LivingSuccess(it!!)
            }, error = {
                loadError(it)
            })
        }
    }

}